package com.lollipop.synthential.concurrency.excutorsdemo;

import cn.hutool.core.lang.Console;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: J.K
 * @Date: 2021-04-27 17:05
 * @Description: 创建线程池:
 * 1.通过Executors工厂方法创建
 * 2.通过new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)自定义创建
 */
public class CreateExecutorDemo2 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(new DemoTask(i));
            Console.log("poolSize:" + threadPoolExecutor.getPoolSize());
            Console.log("corePoolSize:" + threadPoolExecutor.getCorePoolSize());
            Console.log("maximumPoolSize:" + threadPoolExecutor.getMaximumPoolSize());
            Console.log("queue:" + threadPoolExecutor.getQueue().size());
            Console.log("completedTaskCount:" + threadPoolExecutor.getCompletedTaskCount());
            Console.log("largestPoolSize:" + threadPoolExecutor.getLargestPoolSize());
            Console.log("keepAliveTime:" + threadPoolExecutor.getKeepAliveTime(TimeUnit.SECONDS));

        }
    }
}

class DemoTask implements Runnable {

    private int taskNum;

    public DemoTask(int taskNum) {
        this.taskNum = taskNum;
    }

    @Override
    public void run() {
        Console.log(StringUtils.center("正在执行" + taskNum, 20, "="));

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Console.log(StringUtils.center("执行完毕" + taskNum, 20, "="));
    }
}